import sqlite3

from mapper.user_mapper import User_mapper
from mapper.score_mapper import Score_mapper


def get_all_log_data(conn):
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM operate_Log")
    return cursor.fetchall()


if __name__ == '__main__':
    db_path: str = "./db/data.db"
    conn = sqlite3.connect(db_path)

    user_mapper: User_mapper = User_mapper(db_path)
    user_data: list = user_mapper.get_all_user_data()
    print(f"找到{len(user_data)}条User表记录")

    score_mapper: Score_mapper = Score_mapper(db_path)
    score_dara: list = score_mapper.get_all_score_data()
    print(f"找到{len(score_dara)}条Score表记录")

    log_data: list = get_all_log_data(conn)
    print(f"找到{len(log_data)}条Log表记录")

    conn.close()

    print("-------------Start Write File----------------")
    with open("./csv/user.csv", "w", encoding="utf-8") as file:
        print("user.csv 写入中...")
        file.write("name,password,is_admin,create_time\n")
        for user in user_data:
            file.write(f"{user[0]},{user[1]},{user[2]},{user[3]}\n")

    with open("./csv/score.csv", "w", encoding="utf-8") as file:
        print("score.csv 写入中...")
        file.write("id,user_name,score,create_time\n")
        for score in score_dara:
            file.write(f"{score[0]},{score[1]},{score[2]},{score[3]}\n")

    with open("./csv/log.csv", "w", encoding="utf-8") as file:
        print("log.csv 写入中...")
        file.write("id,user_name,level,operate,create_time\n")
        for log in log_data:
            file.write(f"{log[0]},{log[1]},{log[2]},{log[3]},{log[4]}\n")

    print("-------------All File Write Done----------------")
    print("文件保存至csv目录中")
